<template>
  <div class="avue-ueditor">
    <div :id="id"></div>
    <el-dialog title="源代码编辑"
               :before-close="handleClose"
               :visible.sync="editor.sourceDialogVisible"
               width="100%"
               fullscreen
               append-to-body>
      <el-input v-model="textarea"
                :disabled="disabled"
                placeholder="请输入源代码"
                :autosize="{ minRows: 10}"
                type="textarea"></el-input>
    </el-dialog>
    <upload-material v-if="editor.materialDialogVisible"
                     :isMore="5"
                     @materialCallBack="materialCallBack" />
  </div>
</template>
<script>
import store from "@/store";
import E from "wangeditor";

const { $, BtnMenu } = E
class SourceMenu extends BtnMenu {
  constructor(editor) {
    const $elem = E.$(`<div class="w-e-menu" data-title="源代码"><i class="el-icon-edit-outline" /></div>`)
    super($elem, editor)
  }
  clickHandler () {
    this.editor.sourceDialogVisible = true
  }
  tryChangeActive () { }
}
class MaterialMenu extends BtnMenu {
  constructor(editor) {
    const $elem = E.$(`<div class="w-e-menu" data-title="素材"><i class="el-icon-orange" /></div>`)
    super($elem, editor)
  }
  clickHandler () {
    this.editor.materialDialogVisible = true
  }
  tryChangeActive () { }
}
E.registerMenu('sourceMenuKey', SourceMenu)
E.registerMenu('materialMenuKey', MaterialMenu)

export default {
  name: "AvueUeditor",
  computed: {
    domId () {
      return "#" + this.id;
    }
  },
  props: {
    id: {
      type: String,
      default: () => {
        return "avue-ueditor-" + Math.ceil(Math.random() * 100);
      },
    },
    options: {
      type: Object,
      default: () => {
        return {};
      },
    },
    height: {
      type: Number,
      default: 300
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    value: {
      type: String,
      default: "",
    },
  },
  data () {
    return {
      textarea: "",
      editor: {
        sourceDialogVisible: false,
        materialDialogVisible: false
      }
    };
  },
  mounted () {
    this.initEditor();
  },
  methods: {
    // 初始化富文本
    initEditor () {
      this.editor = Object.assign(new E(this.domId), this.editor)
      // 编辑区域内容改变事件
      this.editor.config.onchange = this.editorOnChange
      // 编辑区域自动获取光标
      this.editor.config.focus = false
      // 全屏菜单按钮
      this.editor.config.showFullScreen = true
      // props属性存在延时
      let initTimer = setTimeout(() => {
        // 编辑区域高度
        this.editor.config.height = this.height
        // 查看时去除其他菜单 只拥有全屏功能
        if (this.disabled) {
          this.editor.config.menus = []
        }
        this.editor.create();
        this.textarea = this.value
        this.editor['txt'].html(this.textarea)
        this.disabledEditor()
        clearTimeout(initTimer)
      }, 0)
    },
    // 是否禁用富文本
    disabledEditor () {
      // 禁用富文本
      if (this.disabled) {
        // 禁用菜单
        // this.editor['disable']()
        // 启用编辑区域
        this.editor.$textElem.attr("contenteditable", false)
      }
      // 启用富文本
      else {
        // 启用菜单
        // this.editor['enable']()
        // 禁用编辑区域
        this.editor.$textElem.attr("contenteditable", true)
      }
    },
    // 富文本内容变化处理
    editorOnChange (newHtml) {
      this.textarea = newHtml;
      this.$emit('input', this.textarea.replace(/&amp;/g, '&'))
    },
    // 选择素材回调
    materialCallBack (materials) {
      this.editor.materialDialogVisible = false
      if (this.disabled) return
      if (materials && materials.length > 0) {
        materials.forEach(material => {
          if (material.bigType == 'image') {
            this.editor.cmd.do('insertHTML', `<img src=${material.url} />`)
          }
          if (material.bigType == 'video') {
            this.editor.cmd.do('insertHTML', `<video src=${material.url} />`)
          }
        });
      }
    },
    initUploadImg () {
      this.editor.config.customUploadImg = (file, insert) => {
        this.uploadFile(file[0], "img").then((res) => {
          insert(res);
        });
      };
    },
    initUploadVideo () {
      this.editor.config.customUploadVideo = (file, insert) => {
        this.uploadFile(file[0], "video").then((res) => {
          insert(res);
        });
      };
    },
    uploadFile (file, fileType) {
      let that = this;
      // return new Promise((resolve, reject) => {
      //   const loading = this.$loading({
      //     lock: true,
      //     text: "Loading",
      //     spinner: "el-icon-loading",
      //     background: "rgba(0, 0, 0, 0.7)",
      //   });
      //   const headers = { "Content-Type": "multipart/form-data" };
      //   let oss_config = store.getters.ossAli;

      //   let param = new FormData();
      //   let url = that.action;
      //   // console.log(file)
      //   param.append("file", file);
      //   let client = getClient({
      //     region: oss_config.region,
      //     endpoint: oss_config.endpoint,
      //     accessKeyId: oss_config.accessKeyId,
      //     accessKeySecret: oss_config.accessKeySecret,
      //     bucket: oss_config.bucket,
      //   });
      //   let newFileName = null;
      //   if (fileType == "img") {
      //     newFileName = generateFileName("img", "jpg");
      //   } else if (fileType == "video") {
      //     newFileName = generateFileName("video", "mp4");
      //   } else {
      //     loading.close();
      //     console.log("不支持的文件格式");
      //     return;
      //   }
      //   client
      //     .put(newFileName, file)
      //     .then((res) => {
      //       console.log(res);
      //       if (res && res.url) {
      //         let url = res.url;
      //         loading.close();
      //         that.addAnnex(url);
      //         resolve(url);
      //       }
      //     })
      //     .catch((err) => {
      //       console.log(err);
      //       loading.close();
      //       reject(err);
      //     });
      // });
    },
    handleClose (done) {
      done();
      if (this.disabled) return
      this.editor.txt.html(this.textarea)
    },
  },
};
</script>
<style lang="scss">
body .w-e-text-container > .w-e-text::-webkit-scrollbar {
  width: 8px !important;
  height: 8px !important;
}
body .w-e-text-container > .w-e-text::-webkit-scrollbar-thumb {
  border-radius: 5px !important;
  box-shadow: 0 0 2px #fff !important;
  background-color: #ddd !important;
}
body .w-e-text-container > .w-e-text::-webkit-scrollbar-track {
  border-radius: 0;
  box-shadow: inset 0 0 2px #fff;
}
</style>
